#!/usr/bin/env sh

## posix way to do sed "in place"

# NOTE: we add the "--system" flag to rm to bypass checks made by the "safe"
# rm scritp in script/rm
#
sed_i() {
  if [ $# -gt 2 ]
  then
    echo "usage: sed-i 'EXPRESSION' FILENAME" >&2
    return 1
  fi
  expr=$1
  filename=$2
  tmp=$(mktemp)
  bak="$filename~"
  trap "rm --system -f \"$tmp\" \"$bak\"" TERM INT
  if sed -e "$expr" "$filename" > "$tmp"
  then
    cp "$filename" "$bak"
    trap "" TERM INT
    cp "$tmp" "$filename"
    rm --system -f "$tmp" "$bak"
  else
    ret=$?
    rm --system -f "$tmp" "$bak"
    return $ret
  fi
}

sed_i "$@"
